package org.diysearch.services;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.diysearch.helpers.PageHelper;
import org.diysearch.helpers.UserHelper;
import org.diysearch.interfaces.Product;
import org.diysearch.models.Page;
import org.diysearch.models.User;
import org.diysearch.products.HtmlProduct;

public class ConfirmAccount extends BaseService {
	private static final Log LOG = LogFactory.getLog(ConfirmAccount.class);
	private String uri;
	
	@Override
	public Product execute() throws Exception {
		String token = request.getParameter("t");
		User user = UserHelper.confirm(token);
		Page page = PageHelper.getPage(uri);
		Product p = new HtmlProduct();
		p.setWriter(writer);
		Map<String,Object> content = new HashMap<String,Object>();
		content.put("page", page);
		if (user == null) {
			// not confirmed. provide an error
			content.put("success", "false");
			LOG.warn("Confirmation fail: " + token);
		} else {
			content.put("success", "true");
			user.setStatus(1);
			int code = UserHelper.save(user);
		}
		p.setCompleted("template:"+page.getTemplate(), request, response, template, content);
		
		return p;
	}

	@Override
	public boolean isWriter() {
		return true;
	}

	@Override
	public String getUri() {
		return uri;
	}

	@Override
	public void setUri(String uri) {
		this.uri = uri;
	}

}
